<?php
class Slog_Db_Driver_Mysql extends Slog_Db_Driver
{
	static protected $_connection;
	protected $qr;
	
	public function __construct()
	{
	}
	
	static public function connect($config)
	{
		self::$_connection = @mysql_connect($config['host'], $config['user'], $config['pass']);
		if (self::$_connection) {
			if (@mysql_select_db($config['name'], self::$_connection)) {
				return true;
			}
		}
		return false;
	}
	
	public function query($sql)
	{
		return ($this->qr = @mysql_query($sql, self::$_connection)) ? true : false;
	}
	
	public function fetch($sql = null)
	{
		if ($sql) $this->query($sql);
		return $this->qr ? @mysql_fetch_object($this->qr) : null;
	}
	
	public function fetchAll($sql = null)
	{
		if ($sql) $this->query($sql);
		
		if ($this->qr) {
			$data = array();
			while ($row = $this->fetch()) {
				$data[] = $row;
			}
			return $data;
		}
		
		return null;
	}
	
	public function fetchValue($sql = null)
	{
		if ($sql) $this->query($sql);
		return $this->qr ? @array_shift(mysql_fetch_array($this->qr)) : null;
	}
	
	public function fetchColumn($sql = null)
	{
		if ($sql) $this->query($sql);
		
		if ($this->qr) {
			$data = array();
			while ($row = $this->fetchValue()) {
				$data[] = $row;
			}
			return $data;
		}
		
		return null;
	}
	
	public function escape($text)
	{
		return mysql_escape_string($text);
	}
	
	public function selectToSQL(Slog_Db_Select $select)
	{
		$sql = "";
		
		// Array: table => alias
		$tables = $select->getTables();
		$fields = $select->getFields();
		
		// Campos de consulta
		$joins = $select->getJoins();
		$fields_sql = array();
		foreach ($joins as $j) {
			$table_name = $j->table;
			$table_alias = $tables[$table_name];
			
			foreach ($j->fields as $field_alias => $field_value) {
				if (preg_match('/^[a-zA-Z_]*$/', $field_value)) {
					$field_value = "`$table_alias`.`$field_value`";
				}
				$fields_sql[] = "$field_value as $field_alias";
			}
		}
		$sql .= 'SELECT ' . implode(', ', $fields_sql) . "\n";
		
		// From
		$froms_sql = array();
		foreach ($joins as $j) if ($j->type == Slog_Db_Select_Join::TYPE_FROM) {
			$table_name = $j->table;
			$table_alias = $tables[$table_name];
			$froms_sql[] = "`$table_name` as `$table_alias`";
		}
		$sql .= 'FROM ' . implode(', ', $froms_sql) . "\n";
		
		// Join
		$joins_sql = array();
		foreach ($joins as $j) if ($j->type != Slog_Db_Select_Join::TYPE_FROM) {
			if ($j->type != Slog_Db_Select_Join::TYPE_LEFT) {
				$sql .= 'LEFT ';
			}
			$sql .= 'JOIN ';
			
			$table_name = $j->table;
			$table_alias = $tables[$table_name];
			$sql .= "`$table_name` as `$table_alias` ";

			$sql .= 'ON (' . $j->where . ')' . "\n";
		}
		
		// Where
		if ($wheres = $select->getWheres()) {
			$sql .= 'WHERE ' . implode("\nAND ", $wheres) . "\n";
		}
		
		return $sql;
	}
}
